package com.tinem.platform.web.gateway.filter;

import com.tinem.platform.module.pojo.co.RedisKeyEnum;
import com.tinem.platform.module.pojo.vo.error.ParamsException;
import com.tinem.platform.module.starter.sdk.MessageCode;
import com.tinem.platform.web.gateway.util.GatewayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className ChannelScopeGatewayFilterFactory
 * @description 防止重放攻击
 * @site 
 * @company 
 * @create 2020-07-03 12:26
 */
@Slf4j
@Component
public class ReplayGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
    int durationMin = 5;
    Duration duration = Duration.ofMinutes(durationMin);

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            String apiRequestId = GatewayUtil.getApiReq(exchange);
            String redisKey = RedisKeyEnum.gateway_replay.getKey(apiRequestId);
            try {
                if(stringRedisTemplate.hasKey(redisKey)){
                    log.warn("api request id repeat; {}",apiRequestId);
                    throw new ParamsException(MessageCode.ERROR_COMMONS_REQUEST_REPEAT,apiRequestId);
                };
                stringRedisTemplate.opsForValue().set(redisKey,"0",duration);
            }catch (Exception e){
                log.error("error redis:{}",redisKey);
                log.error("",e);
            }
            return chain.filter(exchange);
        };
    }
}
